package com.xiaolong.redis.aspectj;

import com.xiaolong.redis.annotation.Lock;
import com.xiaolong.redis.factory.LockHandlerFactory;
import com.xiaolong.redis.handle.LockHandler;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.lang.reflect.Method;


@Aspect
public class LockAspect {

    private static final Logger logger = LoggerFactory.getLogger(LockAspect.class);

    @Pointcut("@annotation(com.xiaolong.redis.annotation.Lock)")
    public void lockPointCut() {
    }

    @Around("lockPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Lock lock = getLockInstance(point);
        LockHandler lockHandler = LockHandlerFactory.routingLockHandler(lock.block());
        return lockHandler.execute(point, lock);
    }

    public Lock getLockInstance(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        return method.getAnnotation(Lock.class);
    }
}
